package com.java.base.exercise.current;

import org.springframework.util.StringUtils;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Author RenPu
 * @Date 2021/9/29 15:02
 * @Version 1.0
 * @Description: JDK 1.7，引入的ForkJoinPool，并行执行的框架
 **/
public class ForkJoinPoolDemo {

    public static void main(String[] args) throws Exception {

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask countTask = new CountTask(1, 5);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(countTask);
        System.out.println("结算结果1 ：" + submit.get());

        CountTask countTask1 = new CountTask(1, 100);
        ForkJoinTask<Integer> submit1 = forkJoinPool.submit(countTask1);
        System.out.println("结算结果2 ：" + submit1.get());

        System.out.println("Main Thread Is Dead ! ! ! !");


    }


    static class CountTask extends RecursiveTask<Integer> {

        private static final long serialVersionUID = 3336021432713606929L;

        private static Integer splitSize = 2;

        private Integer startValue, endValue;

        public CountTask(Integer startValue, Integer endValue) {
            this.startValue = startValue;
            this.endValue = endValue;
        }

        @Override
        protected Integer compute() {
            int sum = 0;
            boolean smart = (endValue - startValue) <= splitSize;
            if (smart) {
                for (int i = startValue; i <= endValue; i++) {
                    sum += i;
                }
            } else {

                int middle = (startValue + endValue) / 2;
                CountTask countTask = new CountTask(startValue, middle);
                CountTask countTask1 = new CountTask(middle + 1, endValue);
                countTask.fork();            //此方法异步执行，凭借这个方法可以创建新任务
                countTask1.fork();
                Integer result = countTask.join();  //该方法负责在计算完成后，返回结果，因此允许一个任务等待另一个任务
                Integer result1 = countTask1.join();
                sum = result + result1;

            }

            return sum;
        }
    }

}
